// cart.js
var util = require("../../utils/util.js")

Page({

  /**
   * 页面的初始数据
   */
  data: {
    foods:{},
    cart:{},
    totalPrice:0,
    totalNum:0,
  },
  addNum:function(event){
    let id = event.currentTarget.dataset.id;
    var cart = this.data.cart;
    cart[id]['num'] = cart[id]['num']+1;
    this.setData({cart:cart});
    this.compute();
  },
  subNum:function(event){
    let id = event.currentTarget.dataset.id;
    var cart = this.data.cart;
    if(cart[id]['num'] > 0){
      cart[id]['num'] = cart[id]['num'] - 1;
    }
    this.setData({ cart: cart });
    this.compute();
  },
  compute:function(){//计算总数
     var cart = this.data.cart;
     var foods = this.data.foods;
     var keys = Object.keys(cart);
     var totalPrice = 0;
     var totalNum = 0;
     for (var i = 0; i < keys.length; i++) {
       totalPrice += cart[keys[i]].num * parseFloat(foods[keys[i]].price);
       totalNum += cart[keys[i]].num;
     } 
     this.setData({
       totalPrice:parseFloat(totalPrice),
       totalNum:totalNum
     });
     var app = getApp();
     app.cart = cart;
  },
  //下单页面
  doOrder:function(){
    wx.navigateTo({
      url: '/pages/components/take/take',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var cart = getApp().cart;
    var rootUrl = getApp().rootUrl;
    //设置初始数量
    var keys = Object.keys(cart);
    for(var i = 0;i<keys.length;i++){
      cart[keys[i]].num = cart[keys[i]].num ? cart[keys[i]].num:1;
    }
    this.setData({
      cart:cart
    });
    
    console.log(cart);
    
    if(cart){
      util.foxlogin({
        success: function (token) {
          var keys = Object.keys(cart);
          keys = JSON.stringify(keys);
        
          wx.request({
            url: rootUrl + "api/foods",
            method: "get",
            data: { fids: keys ,token:token},
            success: function (responseData) {
              console.log(responseData);

              var foods = {};
              var data = responseData.data;
              for(var i =  0;i<data.length;i++){
                foods[data[i]['id']] = data[i];
              }
              console.log(foods);
              that.setData({foods:foods});         

              that.compute();     
            }
          });     
        }
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})